package de.rwth.dbis.ugnm.resource;

import java.net.URI;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import de.rwth.dbis.ugnm.entity.User;
import de.rwth.dbis.ugnm.service.UserService;

@Path("/users")
@Component
@Scope("request")
public class UsersResource {

	@Autowired
	UserService userService;

	@GET
	@Produces("application/json")
	public String getUsers(@Context UriInfo ui) {
		URI buri = ui.getBaseUri();
		
		System.out.println("Base URI: " + buri.toASCIIString() + " " + ui.getAbsolutePath().toASCIIString());
		List<User> users = userService.getAll();
		Iterator<User> usit = users.iterator();
		
		StringBuffer b = new StringBuffer();
		b.append("[");
		while(usit.hasNext()){
			User u = usit.next();
			b.append("\"" + ui.getAbsolutePath().toASCIIString() + "/" + u.getLogin() + "\"");
			if(usit.hasNext()){
				b.append(",");
			}
		}
		b.append("]");
		
		return b.toString();
	}
	
	@PUT
    @Consumes("application/json")
    public Response putUser(JSONObject o) throws JSONException {
        
        if (o != null && 
        		o.has("login") && 
        		o.has("name") && 
        		o.has("pass")){
        	User nu = new User();
        	nu.setLogin((String) o.get("login"));
        	nu.setPass((String) o.get("pass"));
        	nu.setName((String) o.get("name"));
        	addIfDoesNotExist(nu);
        }
		
		return Response.noContent().build();
    }
	
	private void addIfDoesNotExist(User user) {
		if(userService.findUser(user) == null) {
			userService.save(user);
		}
	}
}

